<template>
  <view class="container">
    <!-- 顶部导航（保持不变） -->
    <view class="navbar">
      <text class="nav-back" @click="back">←</text>
      <text class="nav-title">情绪周报</text>
      <view class="nav-empty"></view>
    </view>

    <!-- 1. 优化后的初始状态：生成引导（修复动画报错） -->
    <view class="init-view" v-if="pageStatus === 'init'">
      <view class="init-card">
        <!-- 情绪可视化图形（绑定动画） -->
        <view class="emotion-visual" :animation="emotionVisualAnim">
          <view class="wave wave-1"></view>
          <view class="wave wave-2"></view>
          <view class="wave wave-3"></view>
          <image src="/static/images/weekly_icon.png" class="emotion-icon" mode="widthFix"></image>
        </view>

        <!-- 文本区域（绑定动画） -->
        <view class="init-text-group" :animation="textGroupAnim">
          <text class="init-title">生成你的专属情绪周报</text>
          <text class="init-desc">一键汇总7天情绪数据，可视化呈现你的情绪变化与规律，帮你更懂自己</text>
          <text class="init-tip">生成仅需1.6秒，数据安全无缓存</text>
        </view>

        <!-- 按钮（绑定动画） -->
        <button class="init-btn" @click="startGenerate" :animation="btnAnim">
          <text class="btn-text">立即生成</text>
          <view class="btn-arrow">→</view>
        </button>
      </view>

      <view class="init-decoration">
        <view class="dot dot-1"></view>
        <view class="dot dot-2"></view>
        <view class="dot dot-3"></view>
      </view>
    </view>

    <!-- 2. 生成中状态：保持不变 -->
    <view class="loading-view" v-if="pageStatus === 'loading'">
      <view class="loading-spinner"></view>
      <text class="loading-text">AI正在分析本周情绪...</text>
    </view>

    <!-- 3. 生成完成：周报内容（保持不变） -->
    <view class="report-view" v-if="pageStatus === 'report'">
      <view class="report-header">
        <text class="report-date">{{ weekDate }}</text>
        <view class="emotion-badge" :style="{ backgroundColor: badgeBg }">
          <text class="badge-text">{{ emotionSummary }}</text>
        </view>
      </view>

      <view class="data-card">
        <view class="data-item">
          <text class="data-num">{{ data.total }}</text>
          <text class="data-name">本周记录</text>
        </view>
        <view class="data-item">
          <text class="data-num">{{ data.positive }}%</text>
          <text class="data-name">正向情绪</text>
        </view>
        <view class="data-item">
          <text class="data-num">{{ data.hotEmo }}</text>
          <text class="data-name">高频情绪</text>
        </view>
      </view>

      <view class="chart-box">
        <text class="chart-title">本周情绪趋势</text>
        <canvas canvas-id="trendCanvas" class="trend-chart"></canvas>
      </view>

      <view class="insight-box">
        <text class="box-title">AI情绪洞察</text>
        <view class="insight-content">
          <text class="insight-text">{{ aiInsight }}</text>
        </view>
      </view>

      <view class="suggest-box">
        <text class="box-title">调节小建议</text>
        <view class="suggest-list">
          <view class="suggest-item" v-for="(item, idx) in aiSuggest" :key="idx">
            <view class="item-icon">{{ idx + 1 }}</view>
            <text class="item-text">{{ item }}</text>
          </view>
        </view>
      </view>

      <view class="btn-group">
        <button class="oper-btn" @click="startGenerate">重新生成</button>
        <button class="oper-btn main-btn" @click="exportReport">保存周报</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      pageStatus: 'init', // 页面状态：init/loading/report
      weekDate: '', // 周报日期范围
      emotionSummary: '', // 情绪总览标签
      badgeBg: '', // 标签背景色
      data: {}, // 核心数据
      aiInsight: '', // AI洞察文本
      aiSuggest: [], // AI建议列表
      chartWidth: 0, // 图表宽度
      dailyScore: [], // 每日情绪分数
      // 新增：动画数据（替代直接DOM操作）
      emotionVisualAnim: '', // 情绪图形动画
      textGroupAnim: '',     // 文本组动画
      btnAnim: ''            // 按钮动画
    };
  },

  onLoad() {
    this.initWeekDate();
    this.chartWidth = uni.getSystemInfoSync().windowWidth - 40;
    // 移除：不在onLoad中调用动画（此时DOM未渲染）
  },

  onReady() {
    // 修复：在onReady中初始化动画（页面渲染完成后）
    this.initAnimation();
  },

  methods: {
    back() {
      uni.switchTab({ url: "/pages/myHome/myHome" });
    },

    // 初始化本周日期范围
    initWeekDate() {
      const now = new Date();
      const day = now.getDay() || 7; // 周日转为7
      const monday = new Date(now);
      monday.setDate(now.getDate() - day + 1); // 本周一
      const sunday = new Date(monday);
      sunday.setDate(monday.getDate() + 6); // 本周日

      const formatDate = (date) => {
        const y = date.getFullYear();
        const m = (date.getMonth() + 1).toString().padStart(2, '0');
        const d = date.getDate().toString().padStart(2, '0');
        return `${y}.${m}.${d}`;
      };
      this.weekDate = `${formatDate(monday)}-${formatDate(sunday)}`;
    },

    // 开始生成周报
    startGenerate() {
          this.pageStatus = 'loading';
          setTimeout(() => {
            this.fillReportData();
            this.pageStatus = 'report';
            
            // 关键修复：等页面切换完成后再绘制图表
            this.$nextTick(() => {
              this.drawTrendChart();
            });
          }, 1600);
        },

    // 填充周报数据
    fillReportData() {
      this.data = { total: 8, positive: 75, hotEmo: '平静' };
      this.emotionSummary = '轻松愉悦';
      this.badgeBg = 'rgba(100, 181, 246, 0.2)';
      this.dailyScore = [
        { day: '一', score: 4.2 },
        { day: '二', score: 3.8 },
        { day: '三', score: 4.5 },
        { day: '四', score: 3.5 },
        { day: '五', score: 4.0 },
        { day: '六', score: 4.8 },
        { day: '日', score: 4.6 }
      ];
      this.aiInsight = `本周你共记录8次情绪，正向情绪占比75%，高频情绪为“平静”，整体状态轻松愉悦。周末情绪更积极（周六4.8分、周日4.6分），周四情绪稍低（3.5分），推测与工作日节奏变化有关。`;
      this.aiSuggest = [
        '周四可尝试午休时听10分钟轻音乐，缓解工作日中期的轻微疲惫',
        '保持周末积极状态，可固定安排一次短途散步或兴趣活动',
        '每晚睡前简单记录1件开心小事，强化积极情绪记忆'
      ];
    },

    // 绘制情绪趋势图
    drawTrendChart() {
      const ctx = uni.createCanvasContext('trendCanvas', this);
      const padding = 25;
      const chartW = this.chartWidth - padding * 2;
      const chartH = 180 - padding * 2;

      // 绘制背景网格
      ctx.setStrokeStyle('#f2f2f2');
      ctx.setLineWidth(1);
      for (let i = 0; i <= 5; i++) {
        const y = padding + (chartH / 5) * i;
        ctx.beginPath();
        ctx.moveTo(padding, y);
        ctx.lineTo(this.chartWidth - padding, y);
        ctx.stroke();
      }
      for (let i = 0; i < 6; i++) {
        const x = padding + (chartW / 6) * i;
        ctx.beginPath();
        ctx.moveTo(x, padding);
        ctx.lineTo(x, 180 - padding);
        ctx.stroke();
      }

      // 绘制情绪折线
      const stepX = chartW / (this.dailyScore.length - 1);
      ctx.setStrokeStyle('#64b5f6');
      ctx.setLineWidth(3);
      ctx.beginPath();
      this.dailyScore.forEach((item, idx) => {
        const x = padding + idx * stepX;
        const y = padding + (5 - item.score) * (chartH / 5);

        if (idx === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);

        // 绘制数据点
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.setFillStyle('#fff');
        ctx.fill();
        ctx.setStrokeStyle('#64b5f6');
        ctx.stroke();

        // 绘制底部日期标签
        ctx.setFontSize(18);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('center');
        ctx.fillText(item.day, x, 180 - padding + 18);
      });
      ctx.stroke();
      ctx.draw();
    },

    // 导出/保存周报
    exportReport() {
      uni.showToast({
        title: '周报已保存至相册',
        icon: 'success',
        duration: 1500
      });
    },

    initAnimation() {
      const animation = uni.createAnimation({
        duration: 500, // 动画时长
        timingFunction: 'ease', // 缓动效果
        delay: 0
      });
      animation
        .opacity(1) // 从透明到不透明
        .translateY(0) // 从下移到原位
        .step({ delay: 0 }); // 延迟0ms
      this.emotionVisualAnim = animation.export();

      animation
        .opacity(1)
        .translateY(0)
        .step({ delay: 200 }); // 延迟200ms
      this.textGroupAnim = animation.export();

      animation
        .opacity(1)
        .translateY(0)
        .step({ delay: 400 }); // 延迟400ms
      this.btnAnim = animation.export();
    }
  }
};
</script>

<style scoped>
/* 页面容器 */
.container {
  min-height: 100vh;
  background-color: #fafafa;
  padding-bottom: 60rpx;
  background-image: linear-gradient(180deg, #fafafa 0%, #f5f9ff 100%);
}

/* 顶部导航 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}
.nav-back { font-size: 32rpx; color: #64b5f6; }
.nav-title { font-size: 34rpx; font-weight: 600; color: #333; }
.nav-empty { width: 32rpx; }

/* 初始状态样式 */
.init-view {
  padding: 60rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.init-card {
  width: 90%;
  background-color: #fff;
  border-radius: 30rpx;
  padding: 60rpx 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(100, 181, 246, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 50rpx;
}

/* 情绪可视化图形（动画初始状态） */
.emotion-visual {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 动画初始状态：透明+下移 */
  opacity: 0;
  transform: translateY(20rpx);
}

/* 波纹动画 */
.wave {
  position: absolute;
  border-radius: 50%;
  background-color: rgba(100, 181, 246, 0.1);
  animation: waveExpand 3s infinite ease-in-out;
}
.wave-1 { width: 100%; height: 100%; animation-delay: 0s; }
.wave-2 { width: 80%; height: 80%; animation-delay: 0.5s; }
.wave-3 { width: 60%; height: 60%; animation-delay: 1s; }
@keyframes waveExpand {
  0% { transform: scale(1); opacity: 0.8; }
  50% { transform: scale(1.1); opacity: 0.4; }
  100% { transform: scale(1); opacity: 0.8; }
}

.emotion-icon {
  width: 120rpx;
  height: 120rpx;
  z-index: 1;
  animation: float 3s infinite ease-in-out;
}
@keyframes float {
  0% { transform: translateY(0); }
  50% { transform: translateY(-10rpx); }
  100% { transform: translateY(0); }
}

/* 文本组（动画初始状态） */
.init-text-group {
  text-align: center;
  gap: 16rpx;
  display: flex;
  flex-direction: column;
  /* 动画初始状态：透明+下移 */
  opacity: 0;
  transform: translateY(20rpx);
}
.init-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #333;
  line-height: 1.3;
}
.init-desc {
  font-size: 24rpx;
  color: #888;
  line-height: 1.6;
  padding: 0 20rpx;
}
.init-tip {
  font-size: 20rpx;
  color: #64b5f6;
  margin-top: 8rpx;
}

/* 按钮（动画初始状态） */
.init-btn {
  width: 80%;
  height: 88rpx;
  background-color: #64b5f6;
  color: #fff;
  font-size: 28rpx;
  border-radius: 44rpx;
  box-shadow: 0 6rpx 20rpx rgba(100, 181, 246, 0.3);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  transition: all 0.3s ease;
  /* 动画初始状态：透明+下移 */
  opacity: 0;
  transform: translateY(20rpx);
}
.init-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 16rpx rgba(100, 181, 246, 0.2);
}
.btn-text { font-weight: 500; }
.btn-arrow { font-size: 30rpx; }

/* 底部装饰 */
.init-decoration {
  position: absolute;
  bottom: 80rpx;
  display: flex;
  gap: 16rpx;
}
.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: rgba(100, 181, 246, 0.2);
}
.dot-1 { animation: blink 2s infinite 0s; }
.dot-2 { animation: blink 2s infinite 0.5s; }
.dot-3 { animation: blink 2s infinite 1s; }
@keyframes blink {
  0% { opacity: 0.5; }
  50% { opacity: 1; }
  100% { opacity: 0.5; }
}

/* 生成中状态 */
.loading-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}
.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #64b5f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.loading-text { margin-top: 30rpx; font-size: 26rpx; color: #666; }

/* 生成完成：周报内容样式 */
.report-view { padding: 20rpx; }
.report-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30rpx; }
.report-date { font-size: 22rpx; color: #666; }
.emotion-badge { padding: 6rpx 20rpx; border-radius: 20rpx; }
.badge-text { font-size: 22rpx; color: #64b5f6; font-weight: 500; }

.data-card {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx 10rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}
.data-item { text-align: center; }
.data-num { display: block; font-size: 36rpx; font-weight: 600; color: #64b5f6; margin-bottom: 8rpx; }
.data-name { font-size: 22rpx; color: #999; }

.chart-box {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 25rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}
.chart-title { font-size: 26rpx; font-weight: 500; color: #333; margin-bottom: 20rpx; display: block; }
.trend-chart {
  width: 100%;
  height: 180rpx;
  /* 增加背景色方便确认canvas是否存在 */
  background-color: #fafafa;
}

.insight-box, .suggest-box {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 25rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}
.box-title { font-size: 26rpx; font-weight: 500; color: #333; margin-bottom: 20rpx; display: block; }

.insight-content {
  padding: 15rpx;
  background-color: #f8f9fa;
  border-radius: 16rpx;
}
.insight-text { font-size: 24rpx; color: #666; line-height: 1.6; }

.suggest-list { padding-left: 10rpx; }
.suggest-item { display: flex; align-items: flex-start; margin-bottom: 25rpx; }
.suggest-item:last-child { margin-bottom: 0; }
.item-icon {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: #64b5f6;
  color: #fff;
  font-size: 20rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
  flex-shrink: 0;
  margin-top: 4rpx;
}
.item-text { font-size: 24rpx; color: #666; line-height: 1.6; flex: 1; }

.btn-group { display: flex; justify-content: space-between; padding: 0 10rpx; }
.oper-btn {
  width: 48%;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 26rpx;
  border: 1px solid #e5e5e5;
  background-color: #fff;
  color: #666;
  box-shadow: none;
}
.oper-btn.main-btn {
  border: none;
  background-color: #64b5f6;
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(100, 181, 246, 0.3);
}

/* 适配小屏幕 */
@media (max-width: 320px) {
  .init-btn { width: 90%; }
  .data-num { font-size: 32rpx; }
  .item-text, .insight-text { font-size: 22rpx; }
  .init-card { width: 95%; padding: 40rpx 20rpx; }
}
</style>
